﻿var logoItemHtml = '' + '<div class="col-xs-3"><img class = "logoItem" src="{src}" />' + '</div>';
var url_toutiao = '';   //即将过时 07-26
var url_source = '';    //站内URL，一般用来显示排版出问题的外链
var access_token = "";
$(function () {
    var param = {};
    AjaxStart("ajax/WxJsApiAccessToken.ashx?get", param, function (data) {
        if (data.code == 0) {
            var s = sign(data.item.JsApi_Ticket, location.href.split('#')[0]);
            access_token = data.item.Access_Token;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。    
                appId: data.item.AppId, // 必填，公众号的唯一标识    
                timestamp: s.timestamp, // 必填，生成签名的时间戳    
                nonceStr: s.nonceStr, // 必填，生成签名的随机串    
                signature: s.signature,// 必填，签名，见附录1    
                jsApiList: ['chooseImage', 'uploadImage']
            });
        }
        else
            Alert(data.msg);
    });
    loadSource();

    $("#subBtn").on("click", submit);
});
wx.ready(function () {
    $("#btnUploadLogo").click(function () {
        console.log("click");
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log(res);
                var imgId = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                wx.uploadImage({
                    localId: imgId, // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        var url =
                            "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + serverId;
                        var upapi = "/Client2/Ajax/Upload.ashx?WxImg&is_cut=1&width=300&height=300&url=" + encodeURIComponent(url);
                        console.log(upapi);                        wait.show();                        $.get(upapi, { }, function (data) {
                            console.log(data);
                            wait.dismiss();
                            if (data.code == 0) {
                                resetLogo(data.item);
                            }
                            else {
                                toast.show(data.msg);
                            }

                        }, "json");                        
                    }
                });
            }
        });
    });

});
// 解析源代码
function loadSource() {
    var url = getQueryString("url");
    if (url == null || url.length == 0) {
        Alert("没用可用的网址");
        return;
    }
    
    // 微信订阅号文章、今日头条 单独处理
    if (url.indexOf("://mp.weixin.qq.com") > 0) {
        loadWxUrl(url);
    } else if (url.indexOf("v.qq.com") > -1) {
        loadQQVideo(url);
    }
    else if (url.indexOf("http://url.cn/") > -1) {
        loadUrlCN(url);
    } else if (url.indexOf("toutiao.com") > -1 || url.indexOf("pstatp.com") > -1 || url.indexOf("http://url.cn/") > -1) {
        loadTouTiao(url);
        loadInfo(url);
    }
    else if (url.indexOf("xw.qq.com") > -1) {
        loadPage(url);
        loadInfo(url);
    }
    else {
        $(".iframe-body").append("<iframe src = '" + url + "'></iframe>");
        initIfm();
        loadInfo(url);
    }
}

//获取网络标题图片等信息
function loadInfo(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetEditInfo", {
        url: url
    },
        fillData, "json");
}

//处理返回的数据
function fillData(data) {
    wait.dismiss();
    if (data.code != 0) {
        wait.show(data.msg);
        return;
    }
    $("#title").val(data.item.title);

    // 默认第一张图片为头图
    if (data.item.imgList.length > 0) {
        $(".logo").attr("src", data.item.imgList[0]);
    }
    $(data.item.imgList).each(function () {
        $("#imgList").append(logoItemHtml.replace(/{src}/, this));
    });

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

function initIfm() {
    var wh = $(window).height(); // 当前网页课件区域高度
    var iframeTop = $(".iframe-body iframe").offset().top; // 框架距顶部的距离
    $(".iframe-body iframe").css("height", wh - iframeTop + "px"); // 把iframe全屏显示
}

function resetLogo(src) {
    $(".logo").attr("src", src);
    $("#imgList").append(logoItemHtml.replace(/{src}/, src));

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

//绑定提交事件
function submit() {
    var title = $("#title").val();
    var url = getQueryString("url");
    if (title.length == 0) {
        toast.show("标题不能为空");
        return;
    }

    var logo = $(".logo").attr("src");
    if (logo == "img/default.png") {
        toast.show("请设置一张分享logo");
        return;
    }
    if (url_source != "")
        url = url_source;
    var ec = encodeURIComponent;
    window.location.href = "to_detail.aspx?type=2&title=" + ec(title) + "&logo=" + ec(logo) + "&url=" + ec(url);
}


//微信链接处理
function loadWxUrl(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            loadInfo(url);
            window.ifm = data.item;
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'javascript:parent.ifm'></iframe>");
            initIfm();
            ifmLoad();
        }
        else {
            toast.show(data.msg);
        }

    }, "json");
}

//今日头条处理
function loadTouTiao(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "";

            var item = data.item;
            if (item.url != null)
                url = item.url;        //默认网址
            if (item.return_url != null && item.return_url != "")
                url = item.return_url; //最后显示的网址
            console.log(url);
            console.log(item);

            if (url.indexOf("toutiao.com") > -1 || url.indexOf("utm_medium=toutiao") > -1) {
                url_source = shared_domain + "/client/page/toutiao.aspx?source_id=" + item.id;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/toutiao.aspx?source_id=" + item.id + "'></iframe>");
            }
            else
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = '" + url + "'></iframe>");
            initIfm();
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

//url.cn 短域名处理
function loadUrlCN(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "", oldUrl = "";

            var item = data.item;
            if (item.url != null) {
                url = item.url;
                oldUrl = item.url;     //粘贴的网址
            }
            if (item.return_url != null)
                url = item.return_url; //重定向后的网址

            //对重定向的网址做处理

            //微信链接处理
            if (url.indexOf("http://mp.weixin.qq.com") > -1) {
                loadInfo(oldUrl);
                url_source = url;
                window.ifm = item.source;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'javascript:parent.ifm'></iframe>");
                initIfm();
                ifmLoad();
            }
            else if (url.indexOf("toutiao.com") > -1) {
                //头条链接处理
                url_source = shared_domain + "/client/page/toutiao.aspx?source_id=" + item.id;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/toutiao.aspx?source_id=" + item.id + "'></iframe>");
            }
            else {
                $(".iframe-body").append("<iframe src = '" + url + "'></iframe>");
                initIfm();
                //loadInfo(url);
            }
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function loadPage(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "";
            if (data.item.url != null)
                url = data.item.url;        //默认网址
            if (data.item.return_url != null)
                url = data.item.return_url; //最后显示的网址
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/qq.aspx?source_id=" + data.item.id + "'></iframe>");
            url_source = shared_domain + "/client/page/qq.aspx?source_id=" + data.item.id;
            initIfm();
            
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function loadQQVideo(url) {
    url = formatQQUrl(url);
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            url_source = shared_domain + "/client/page/qq.aspx?source_id=" + data.item.id;
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/qq.aspx?source_id=" + data.item.id + "'></iframe>");
            initIfm();
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function ifmLoad() {
    setTimeout(function () {
        //解决ios微信链接内容显示不全Bug
        if ($("#ifmUrl").attr("src").indexOf("http") != 0 && navigator.userAgent.toLowerCase().indexOf("iphone os") != -1) {
            $("#ifmUrl").contents().find("body").css("width", $(window).width() + "px");
        }

        $("#ifmUrl").contents().find("[data-src]").each(function () {
            $(this).attr("src", $(this).attr("data-src"));
        });

        reloadWxVideo();
    }, 500);
}

function formatQQUrl(url) {
    if (url.indexOf("//v.qq.com") > -1) {
        if (url.indexOf("//v.qq.com/x/page") > -1) {
            var newUrl = "https://m.v.qq.com/page/7/X/6/";
            var htmlName = "";
            if (url.lastIndexOf("/") > -1)
                htmlName = url.substring(url.lastIndexOf("/") + 1);
            url = newUrl + htmlName;
        }
        else {
            url = url.replace("http://", "https://");
            url = url.replace("//v.qq.com", "//m.v.qq.com");
            url = url.replace("/x/cover/", "/cover/k/");
            url = url.replace(".com/prev/", ".com/cover/");
        }
    }
    return url;
}